import baseUrl from "./url.js"
import store from "../store/index.js"
const request = (url, data) => {
	return new Promise((resolve, reject) => {
		const httpDefaultOpts = {
			url: baseUrl.url + url,
			data,
			method: "POST",
			dataType: "json",
			header: {
				"x-requested-with": "XMLHttpRequest",
				"content-type": "application/x-www-form-urlencoded",
				"Authorization": uni.getStorageSync("token"),
			}
		} 
		uni.request(httpDefaultOpts).then(resuet => {
			if (resuet.statusCode === 200) {
				if(resuet.data.code === 0) {  //请求成功
					resolve(resuet.data)
				} else if (resuet.data.code === -2) {  //token失效
					uni.removeStorageSync("token")
					uni.removeStorageSync("address")
					store.state.isLogin = false
					store.state.account = ""
					uni.showToast({
						title: "登录已失效，重新登录",
						icon: "none"
					})
					setTimeout(()=>{
						uni.navigateTo({
							url: "/pages/index/index"
						})
						store.dispatch("initWeb3")
					}, 1000)
				} else {
					console.log("发生错误的URL", url, data, resuet.data)
					resolve(resuet.data)
				}
			} else {
				console.log("发生错误的URL", url, data)
				reject(resuet)
			}
		}).catch((response) => {
			reject(response)		
		})
	})
}

export default request